<?php

namespace XWAM\Model;

/**
 * LinksModel 类
 *
 * @since 1.0 <2015-11-10> SoChishun <14507247@qq.com> Added.
 */
class LinksModel extends AppbaseModel {

    protected $tableName = 't_porg_link';

    function save_link() {
        $rules = array(
            array('title', 'require', '标题无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('link_url', 'require', '链接地址无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('status', 'number', '状态无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('user_name', 'require', '用户无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->getError());
        }
        $msg = \Common\Controller\UploadHandlerController::upload(array('savePath' => 'Links/', 'skipEmpty' => true));
        if (is_array($msg) && isset($msg['image_url'])) {
            $fileinfo = $msg['image_url'];
            $this->data['image_url'] = $fileinfo['filepath'];
            $this->data['file_size'] = format_bytes($fileinfo['size']);
        }
        if (empty($this->id)) {
            unset($this->data['id']);
            $result = $this->add();
        } else {
            $result = $this->save();
        }
        return $this->returnMsg($result);
    }

    function change_sort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    function delete_link($id) {
        $paths = $this->where(array('id' => array('in', $id)))->getField('image_url', true);
        $result = $this->delete($id);
        if ($result) {
            foreach ($paths as $path) {
                if ($path && file_exists($path)) {
                    @unlink($path);
                }
            }
        }
        return $this->returnMsg($result);
    }

}
